package com.lengxf.pay.common.bean;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.lengxf.pay.common.MapConvert;
import com.lengxf.pay.common.config.GlobalObjectMapper;

import java.util.Map;
import java.util.TreeMap;


public interface Param {

    default Map<String, Object> toMap(Boolean deepMapToJson) {
        Map<String, Object> map = GlobalObjectMapper.beanToMap(this);
        return deepMapToJson ? MapConvert.deepMapToJson(map) : map;
    }

    default Map<String, Object> toMap() {
        return toMap(true);
    }

    default String toJson() {
        return GlobalObjectMapper.beanToJson(this);
    }

    default String toXml() {
        return XmlUtil.beanToXml(this).toString();
    }


    //转换为 k1=v1&k2=v2
    default String toKvStr() {
        TreeMap<String, Object> params = new TreeMap<>(toMap());
        StringBuilder sb = new StringBuilder();
        if (MapUtil.isNotEmpty(params)) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                sb.append(String.format("%s=%s", key, GlobalObjectMapper.beanToJson(value)).concat("&"));
            }
        }
        return StrUtil.subBefore(sb.toString(), "&", true);
    }


}
